let Vue;

function install(_Vue) {
    Vue = _Vue;

    Vue.mixin({
        beforeCreate() {
            if (this.$options.store) {
                Vue.prototype.$store = this.$options.store;
            }
        },
    });
}

class Store {
    constructor(options) {
        this.$options = options;
        // state 数据是响应式的
        this.state = new Vue({
            data: this.$options.state,
        });

        // 接收 mutations
        this.$mutations = this.$options.mutations || {};

        // 接收 actions
        this.$actions = this.$options.actions || {};

        // 接收 getters
        this.$getters = this.$options.getters || {};
        this.handleGetters();
    }

    /**
     * commit 函数，修改 state
     * @param {*} name
     * @param {*} arg
     */
    commit = (name, arg) => {
        this.$mutations[name](this.state, arg);
    };

    /**
     * dispatch 函数，异步操作
     * @param {*} name
     * @param {*} arg
     */
    dispatch = (name, arg) => {
        this.$actions[name]({ commit: this.commit, state: this.state }, arg);
    };

    /**
     * 处理响应式
     */
    handleGetters() {
        this.getters = {};
        Object.keys(this.$getters).forEach((key) => {
            Object.defineProperty(this.getters, key, {
                get: () => {
                    return this.$getters[key](this.state);
                },
            });
        });
    }
}

export default { Store, install };
